<template>
  <div class="pagination">
    <button
      :disabled="currentPage == 1"
      @click="$emit('setPageNo', currentPage - 1)"
    >
      上一页
    </button>
    <button v-if="isShowFirst" @click="$emit('setPageNo', 1)">1</button>
    <button v-if="isShowFirstPort" disabled>···</button>

    <button
      v-for="s in startNumAndendNum.end"
      :key="s"
      v-show="isShowNum(s)"
      @click="$emit('setPageNo', s)"
      :class="{ active: s == currentPage ? true : false }"
    >
      {{ s }}
    </button>

    <button v-if="isShowEndPort" disabled>···</button>
    <button v-if="isShowEnd" @click="$emit('setPageNo', totalPage)">
      {{ totalPage }}
    </button>
    <button @click="$emit('setPageNo', currentPage + 1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["currentPage", "pageSize", "total", "countains"],
  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    startNumAndendNum() {
      let start = 0,
        end = 0;
      let { currentPage, countains, totalPage } = this;
      if (countains > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        start = currentPage - parseInt(countains / 2);
        end = currentPage + parseInt(countains / 2);
        if (start < 1) {
          start = 1;
          end = countains;
        }
        if (start > totalPage) {
          end = totalPage;
          start = totalPage - countains + 1;
        }
      }

      return { start, end };
    },
    isShowFirst() {
      return this.startNumAndendNum.start >= 2;
    },
    isShowFirstPort() {
      return this.startNumAndendNum.start >= 3;
    },
    isShowEnd() {
      return this.startNumAndendNum.end <= this.totalPage - 1;
    },
    isShowEndPort() {
      return this.startNumAndendNum.end <= this.totalPage - 2;
    },
  },
  methods: {
    isShowNum(s) {
      return this.startNumAndendNum.start <= s && s <= this.totalPage;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
